package com.strongbj.iot.devices.newlight.request.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.common.NetMapping;
import com.strongbj.iot.devices.newlight.entity.CloseTagData;
import com.strongbj.iot.devices.newlight.entity.CloseTagReturnData;
import com.strongbj.iot.devices.newlight.entity.Reader;
import com.strongbj.iot.devices.newlight.entity.T;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightOSMessageFactory;
import com.strongbj.iot.devices.newlight.response.handle.LowBatteryResponseHandle;
import com.strongbj.iot.devices.newlight.service.ReaderService;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

public class CloseTagHandle implements IMessageHandle<NewLightMQMessage, Object> {

	private static Logger logger = LogManager.getLogger(LowBatteryResponseHandle.class.getName());

	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	private ReaderService readerService = (ReaderService) ContextUtils.getBean("readerService");

	private NewLightOSMessageFactory newLightOSMessageFactory = (NewLightOSMessageFactory) ContextUtils
			.getBean("newLightOSMessageFactory");

	@Override
	public boolean isHandle(NewLightMQMessage msg) {
		if (msg.getActioncode().equals("closeTag")) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightMQMessage msg) {
		logger.info("====收到标签关闭====");
		CloseTagData data = ((JSONObject) msg.getPostdata()).toJavaObject(CloseTagData.class);
		if (data.getCards().size() > 5) {
			// 返回失败MQ消息
			NewLightMQMessage mes = new NewLightMQMessage();
			mes.setActioncode("closeTagReturn");
			mes.setGUID(msg.getGUID());
			CloseTagReturnData ctrd = new CloseTagReturnData();
			ctrd.setErrCode("20002");
			ctrd.setResult("fail");
			mes.setPostdata(ctrd);
			logger.info("=========closeTagReturn=======" + JSON.toJSONString(mes));
			topicSender.send("wh.reader.command.response", JSON.toJSONString(mes));
		} else {
			// 循环给reader发送关闭命令
			for (int i = 0; i < data.getDevsn().size(); i++) {
				QueryWrapper<Reader> query = new QueryWrapper<Reader>();
				query.eq("code_", data.getDevsn().get(i));
				Reader reader = readerService.getOne(query);
				for (int ii = 0; ii < data.getCards().size(); ii++) {
					byte[] sendData = new byte[5];
					String tag = data.getCards().get(i).getCard();
					byte[] d = ByteUtil.address4ToBytes(tag);
					System.arraycopy(d, 0, sendData, 0, 4);
					sendData[4] = ByteUtil.bitStringToByte("00111100");
					byte[] req = newLightOSMessageFactory.createNewLightOSMessage(
							ByteUtil.addressToBytes(reader.getCode()), (byte) 0x04, sendData, T.getTimeStamp());
					ByteBuf bs = Unpooled.copiedBuffer(req);
					Channel channel = NetMapping.getInstance().getChannel(reader.getIp());
					ChannelFuture cf = channel.writeAndFlush(bs);
					cf.addListener(new ChannelFutureListener() {

						@Override
						public void operationComplete(ChannelFuture future) throws Exception {
							if (future.isSuccess()) {
								logger.info("发送关闭标签命令成功 设备编号:{} 标签编码={} 命令={}  ", reader.getCode(), tag,
										ByteUtil.byteArrToHexString(req, true));
							} else {
								logger.debug("发送关闭标签命令失败 设备编号:{} 标签编码={} 命令={}  ", reader.getCode(), tag,
										ByteUtil.byteArrToHexString(req, true));
							}
						}

					});
				}
			}
		}
		return null;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub

	}

}
